<template>
    <div class="children_content">
        <div id="efContainer" style="width: 100%; height: 100%; position: relative;">
            <!-- 设置容器相对定位 -->
            <div v-for="node in nodes" :key="node.id" :id="node.id" :class="node.className" :style="node.style">{{ node.label }}</div>
        </div>
        <!-- <button>添加节点</button> -->
        <Button type="primary" icon="md-add" @click="addNode('square')">正方形</Button>
        <button @click="deleteNode">删除节点</button>
        <button @click="saveNodes">保存节点</button>
    </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, nextTick } from 'vue';
import { jsPlumb } from 'jsplumb';

const nodes = ref([
    { id: 'node1', label: '开始', style: { position: 'absolute', left: '50px', top: '50px' }, className: 'oval' },
    { id: 'node2', label: '结束', style: { position: 'absolute', left: '250px', top: '250px' }, className: 'oval' }
]);

let jsPlumbInstance;
let selectedConnection = null; // 用于存储当前选中的连接线
let inputElement = null;  // 用于存储文本输入框

onMounted(() => {
    jsPlumbInstance = jsPlumb.getInstance({
        Container: 'efContainer', // 容器
        Anchor: 'Continuous', // 自动调整锚点
        Anchors: ['Right', 'Left', 'Top', 'Bottom'], // 给每个端点分配正确的锚点位置
        EndpointStyle: { radius: 6, fill: '#818FB4' },
        PaintStyle: { stroke: '#818FB4', strokeWidth: 2 }, // 连接线的样式
        HoverPaintStyle: { stroke: '#498FFF' },
        EndpointHoverStyle: { fill: '#498FFF' },
        ConnectionOverlays: [
            [
                'Arrow',
                { location: 1, visible: true, paintStyle: { stroke: '#818FB4', fill: '#818FB4' } }
            ]
        ], // 箭头配置
        Connector: ['Flowchart'], // 连接器，支持直角连接
        DragOptions: { cursor: 'crosshair', zIndex: 2000 }, // 拖拽时的配置
        Scope: 'jsPlumb_DefaultScope'
    });

    // 初始化已有节点的端点和拖拽功能
    nodes.value.forEach(node => {
        addEndpoints(node.id);
        jsPlumbInstance.draggable(node.id);
    });

    jsPlumbInstance.bind('connection', (evt) => {
        console.log('Connection established', evt);
    });

    jsPlumbInstance.bind('connectionDetached', (evt) => {
        console.log('Connection detached', evt);
    });

    // 监听连接线的单击事件
    jsPlumbInstance.bind('click', (connection) => {
        selectedConnection = connection;  // 设置当前选中的连接线
        console.log("Connection clicked:", connection);
    });

    // 监听键盘事件，回退键删除选中的连接线
    window.addEventListener('keydown', (event) => {
        if (event.key === 'Backspace' && selectedConnection) {
            jsPlumbInstance.deleteConnection(selectedConnection); // 删除选中的连接线
            selectedConnection = null;  // 清除选中的连接线
        }
    });

    // 监听连接线的双击事件
    jsPlumbInstance.bind('dblclick', (connection, originalEvent) => {
        const midpoint = getConnectionMidpoint(connection);  // 获取连接线的中点位置
        showInputAtConnection(midpoint, connection);  // 显示输入框
    });
});

// 计算连接线的中点
const getConnectionMidpoint = (connection) => {
    const sourcePos = connection.source.getBoundingClientRect();
    const targetPos = connection.target.getBoundingClientRect();

    const midpoint = {
        left: (sourcePos.left + targetPos.left) / 2,
        top: (sourcePos.top + targetPos.top) / 2
    };

    return midpoint;
};

// 在连接线的中点显示输入框
const showInputAtConnection = (midpoint, connection) => {
    if (inputElement) {
        inputElement.remove();  // 删除已存在的输入框
    }

    inputElement = document.createElement('input');
    inputElement.type = 'text';
    inputElement.value = connection.getLabel() || '';  // 默认显示连接线的标签，如果没有则为空
    inputElement.style.position = 'absolute';
    inputElement.style.left = `${midpoint.left - 50}px`; // 在连接线中间显示
    inputElement.style.top = `${midpoint.top - 15}px`;
    inputElement.style.zIndex = 1000;
    document.body.appendChild(inputElement);

    // 聚焦到输入框
    inputElement.focus();

    // 监听输入框失去焦点事件，保存文本
    inputElement.addEventListener('blur', () => {
        connection.setLabel(inputElement.value);  // 设置连接线的标签
        inputElement.remove();  // 删除输入框
        inputElement = null;  // 清除输入框引用
    });
};

// 为节点添加端点
const addEndpoints = (nodeId) => {
    jsPlumbInstance.addEndpoint(nodeId, {
        anchor: 'Right',
        isSource: true,
        isTarget: true,
        maxConnections: -1
    });
    jsPlumbInstance.addEndpoint(nodeId, {
        anchor: 'Left',
        isSource: true,
        isTarget: true,
        maxConnections: -1
    });
    jsPlumbInstance.addEndpoint(nodeId, {
        anchor: 'Top',
        isSource: true,
        isTarget: true,
        maxConnections: -1
    });
    jsPlumbInstance.addEndpoint(nodeId, {
        anchor: 'Bottom',
        isSource: true,
        isTarget: true,
        maxConnections: -1
    });
};

const addNode = (type) => {
    const newNode = {
        id: `node${nodes.value.length + 1}`,
        label: '新节点',
        style: { position: 'absolute', left: `${Math.random() * 300}px`, top: `${Math.random() * 300}px` },
        className: type
    };
    nodes.value.push(newNode);

    nextTick(() => {
        addEndpoints(newNode.id);
        jsPlumbInstance.draggable(newNode.id);
    });
};

const deleteNode = () => {
    const lastNode = nodes.value.pop();
    jsPlumbInstance.removeAllEndpoints(lastNode.id);
};

const saveNodes = () => {
    const nodesData = nodes.value.map(node => ({
        id: node.id,
        label: node.label,
        style: node.style
    }));
    console.log('Saved nodes:', nodesData);
};

onBeforeUnmount(() => {
    jsPlumbInstance.deleteEveryConnection();
    jsPlumbInstance.destroy();
});
</script>

<style scoped lang="scss">
.flowChart_box {
    background-color: #fff;
}
.oval {
    width: 100px;
    height: 50px;
    background-color: #f0f0f0;
    border: 1px solid #ccc;
    text-align: center;
    line-height: 50px;
    position: absolute;
    border-radius: 50px;
}

.square {
    width: 100px;
    height: 50px;
    background-color: #f0f0f0;
    border: 1px solid #ccc;
    text-align: center;
    line-height: 50px;
    position: absolute;
}

.rhombus {
    width: 100px;
    height: 50px;
    background-color: #f0f0f0;
    border: 1px solid #ccc;
    text-align: center;
    line-height: 50px;
    position: absolute;
}

:deep(.jtk-overlay) {
    background-color: #fff;
    padding: 5px;
}
</style>